/**
 * Created by admin on 2016/10/26.
 */
var assert = require('../assert.js');
// 提交测试
exports.redirectWX = function (req, res, next) {

    var params = req.query.params;
    if(!params){
        res.send('<script>alert("请求错误");history.go(-1)</script>')
    }
    //反解参数,根据不同的来源进行不同的appKey赋值
    var statDict = JSON.parse(new assert.base64Assert().decode(params));
    var wxAppId = '';
    var wxSecret = '';
    switch (statDict.from){
        case 'hm':
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
        case 'seagou':
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
        case 'koudai':
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
        case 'normal':
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
        default :
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
    }
    var WinXinRedirect = 'parse.lovepinyao.com';
    console.log(params);
    var WinXinLogin = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wxAppId +'&' +
        'redirect_uri=http%3A%2F%2F'+ WinXinRedirect +'%2FwxLogin?paramsStr='+params+'&'+
        'response_type=code&' +
        'scope=snsapi_userinfo&' +
        'state=seagou' +
        '#wechat_redirect';
    res.redirect(WinXinLogin);

};

exports.wxLogin = function (req, res) {
    var code = req.query.code;
    var state = req.query.state;
    var params = req.query.paramsStr;
    if(params){
        state = params;
    }

    var stateDic = JSON.parse(new assert.base64Assert().decode(state));
    if (!code) {
        res.redirect(returnErrorLogin(stateDic,"未找到Code: " + access_token_obj.errmsg));
        return
    }
    if(state){
        var oldStateDic = stateDic;
        var stateType = '';
        var from = stateDic.from;
        stateType = 'login';
        var dataEnv = stateDic.env ? stateDic.env : 'normal';
    }
    //获取到了code,则拿着code请求微信的授权
    var wxAppId = '';
    var wxSecret = '';
    switch (from){
        case 'hm':
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
        case 'seagou':
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
            break;
        default:
            wxAppId = 'wx966722d472a4146d';
            wxSecret = '5f09e4cddceeeee637ef7d4fde68832a';
    }
    var AuthUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + wxAppId + '&secret=' + wxSecret + '&code=' + code + '&grant_type=authorization_code';
    //请求access_token
    assert.apiRequest(AuthUrl).then(function (access_token_obj) {
        if (access_token_obj.errcode) {
            res.redirect(returnErrorLogin(stateDic,"获取access_token失败,原因为: " + access_token_obj.errmsg));
            return
        }
        console.log(access_token_obj);
        //成功获取access_token,接下来获取用户信息
        var UserInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token_obj.access_token + '&openid=' + access_token_obj.openid + '&lang=zh_CN';
        assert.apiRequest(UserInfoUrl).then(function (userInfoObj) {
            if (userInfoObj.errcode) {
                res.redirect(returnErrorLogin(stateDic,"获取微信用户信息失败,原因为: " + userInfoObj.errmsg));
                return
            }
            console.log(userInfoObj);
            assert.apiParseRequest('GET', '/wxUnionIdLogIn?wxUnionId='+userInfoObj.unionid,{},'',dataEnv).then(function (loginResults) {
                if (loginResults.objectId) {
                    var returnObj = {};
                    returnObj.userId = loginResults.objectId;
                    returnObj.openId = access_token_obj.openid;
                    returnObj.unionId = userInfoObj.unionid;
                    returnObj.paramsRedirect = stateDic;
                    assert.apiParseRequest('POST', '/functions/setUserOpenId', {userId: loginResults.objectId, openId: access_token_obj.openid},'',dataEnv);
                    res.redirect('http://' + stateDic.host + stateDic.path + '?params=' + new assert.base64Assert().encode(JSON.stringify(returnObj)));
                } else {
                    //登录失败,表示没有这个用户,进行注册逻辑
                    var dataUser = {
                        username: 'weixin_' + userInfoObj.unionid,
                        password: 'weixin_' + userInfoObj.unionid,
                        nickname: userInfoObj.nickname,
                        sex: userInfoObj.sex == 0 ? '' : userInfoObj.sex == 1 ? '男' : '女',
                        avatar: userInfoObj.headimgurl,
                        signFrom: from,
                        userType: 'normal',
                        unionId: userInfoObj.unionid,
                        wxOpenId:access_token_obj.openid,
                        age: '',
                        birthday: '',
                        deviceType: ''
                    };
                    assert.apiParseRequest('post', '/users', dataUser,'',dataEnv).then(function (results) {
                        if (results.objectId) {
                            assert.apiParseRequest('post', '/functions/addUserPoints', {userId:results.objectId,addType:'OauthSign_wx',number:50},'',dataEnv);
                            var returnObj = {};
                            returnObj.userId = results.objectId;
                            returnObj.openId = access_token_obj.openid;
                            returnObj.unionId = userInfoObj.unionid;
                            returnObj.paramsRedirect = stateDic;
                            res.redirect('http://' + stateDic.host + stateDic.path + '?params=' + new assert.base64Assert().encode(JSON.stringify(returnObj)));
                        } else {
                            res.redirect(returnErrorLogin(stateDic,"自动第三方注册失败"));
                        }
                    }, function (error, err) {
                        res.redirect(returnErrorLogin(stateDic,"注册用户失败"));
                    });
                }
            }, function (error, err) {
                res.redirect(returnErrorLogin(stateDic,"微信账号直接登陆失败"));
            });
        }, function (err) {
            res.redirect(returnErrorLogin(stateDic,"获取微信用户信息失败"));
        });
    }, function (err) {
        res.redirect(returnErrorLogin(stateDic,"获取token失败"));
    });
};

function returnErrorLogin(stateDict,err){
    return 'http://'+stateDict.host + stateDict.path + '?loginErr='+err;
}